<?php


namespace app\common\service;


use app\common\model\Goods;
use app\common\model\MinusItem;
use app\common\model\Project;
use GatewayWorker\Lib\Db;

/**
 * 项目减免管理服务
 *
 * Class MinusService
 * @package app\common\service
 */
class MinusService
{
    /**
     * 保存减免商品或者项目
     *
     * @param $minus_id  减免ID
     * @param $data_list 提交数据
     * @param $source 来源:1=减免的项目，2=被减免的商品
     */
    public static function saveMinusItem($minus_id,$data_list,$source) {
        foreach ($data_list as $key => $val) {
            if ($key == 'goods') {
                if(!empty($val)){
                    $data = Goods::where(['id'=>$val])->find();
                    if($data->status == '0'){
                        return ['status'=>false,'msg'=>'【'.$data->getAttr('name').'】不可售，无法添加组合下单'];
                    }
                    self::addGoods($minus_id,$val,$source);
                }

            }
            if ($key == 'project') {
                if(!empty($val)){
                    self::addProject($minus_id,$val,$source);
                }
            }
            return ['status'=>true];
        }
    }



    /**
     * 添加减免商品
     *
     * @param $minus_id  减免ID
     * @param $goods_list  提交减免商品
     * @param $source  来源:1=减免的项目，2=被减免的项目
     */
    public static function addGoods($minus_id,$goods_list,$source)
    {

        foreach ($goods_list as $item_id) {
            $goods_info = Goods::get($item_id);
            if (!empty($goods_info)) {
                MinusItem::create([
                    'minus_id' => $minus_id,
                    'item_id' => $item_id,
                    'item_type' => 'goods',
                    'source' => $source,
                    'name' => $goods_info['name'],
                    'price' => $goods_info['price']
                ]);
            }
        }
    }


    /**
     * 添加减免项目
     *
     * @param $minus_id     减免ID
     * @param $project_list 提交减免项目数据
     * @param $source 来源:1=减免的项目，2=被减免的项目
     */
    public static function addProject($minus_id,$project_list,$source)
    {
        foreach ($project_list as $item_id) {
            $project_info = Project::get($item_id);
            if (!empty($project_info)) {
                MinusItem::create([
                    'minus_id' => $minus_id,
                    'item_id' => $item_id,
                    'item_type' => 'project',
                    'source' => $source,
                    'name' => $project_info['name'],
                    'price' => $project_info['price']
                ]);
            }
        }
    }





}